<?php
namespace Home\Controller\Mobile;
use Think\Controller;
/**
 * 微信网页授权
 */
 
class AuthController extends Controller {
	    
    public function back(){
 		$jsxcode = I("request.jsxcode");
 		
 		$par['flag'] = 'system';
		$list = M('sxkj_offline_data')->where($par)->find();
		$list = json_decode($list['data'],true);

		$face = I("request.face");		
		if(!empty($face)){  
			$face = str_replace("@","/", $face);
		}	
		
        $appId = $list['appid'];
		$appSecret = $list['secret']; //appsecret,微信公众号基本设置里面找
        $code = $_GET['code']; //接收上面url返回code，5分钟有效期，code直接$_GET['code']接收，vdump($code);die();
		//授权结束后的回调网址
		$path = $_REQUEST['state'];
        //通过下面url获取access_t和 openid，具体看代码
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code';
        $data = json_decode($this->curl($url),true);//调取function.php封装的CURL函数

		$userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$data['access_token']}&openid={$data['openid']}";
		$userinfo_json = $this->curl($userinfo_url);
		$userinfo_array = json_decode($userinfo_json,ture);
		if(empty($userinfo_array['openid'])){
			echo 'OPENID为空';exit;
		}
		
		$par['openid'] = $userinfo_array['openid'];	
		$user = M('sxkj_offline_user')->where($par)->find(); 
		$nickname = $this->filterNickname($userinfo_array['nickname']);
		if(empty($user)){
			$arr = array(
				'openid' =>$userinfo_array['openid'],
				'nickname' =>$nickname,
				'avatar' =>$userinfo_array['headimgurl'],
				'sex' =>$userinfo_array['sex'],	
				'add_time'=>time(),
			);	
			//上级id
            if(!empty($jsxcode)){
                $par_sup['jsxcode'] = $jsxcode;
                $sup_uid = M('sxkj_offline_user')->where($par_sup)->getField('id');
                if(!empty($sup_uid)){
                    $arr['sup_promoterid'] = $sup_uid;
                }
            }
			$result = M('sxkj_offline_user')->data($arr)->add();
			if( $result !== false ){
				//用户表增加邀请码
				$data_user['jxscode'] = $result.$this->getRandom(4);
				$data_user['is_distributor'] = 1;
				M('sxkj_offline_user')->where('id=%d',$result)->save($data_user);
				
    			$userarr = array(
    				'uid'=>$result,
    			);
    			session('user',$userarr);
    		}
		}else{
			$arr = array(
				'nickname' =>$nickname,
				'avatar' =>$userinfo_array['headimgurl'],
				'sex' =>$userinfo_array['sex'],	
			);	
			M('sxkj_offline_user')->where($par)->save($arr);
			$userarr = array(
				'uid'=>$user['id'],
			);
			session('user',$userarr);
		}
		header('Location:'.$this->get_http().'://'.$_SERVER['HTTP_HOST'].U('Home/Mobile/Index/index'));exit;
    }
    
    public function get_http(){
		if($_SERVER['HTTPS'] === 1){  //Apache  
			$h = 'https';  
		}elseif($_SERVER['HTTPS'] === 'on'){ //IIS  
			$h = 'https'; 
		}elseif($_SERVER['SERVER_PORT'] == 443){ //其他  
			$h = 'https'; 
		}else{
			$h = 'http';
		}
		return $h;		
   	}
    
    public function curl($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
    
  	/**
  	 * 昵称表情过滤
  	 */
  	public function filterNickname($nickname){
	    $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickname);
	    $nickname = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nickname);
		$nickname = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nickname);
	    $nickname = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nickname);
		$nickname = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nickname);
		$nickname = str_replace(array('"','\''), '', $nickname);
		return addslashes(trim($nickname));
  	}
	
	public function httpGet($url){
        if(function_exists('curl_init')){
	        $ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL, $url);
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	        curl_setopt($ch, CURLOPT_HEADER, 0);
	        $return = curl_exec($ch);
	        curl_close($ch); 
	        return $return;
	    }
	    return false;
    }
    
    /*<li>-41001: encodingAesKey 非法</li>
	<li>-41003: aes 解密失败</li>
	<li>-41004: 解密后得到的buffer非法</li>
	<li>-41005: base64加密失败</li>
	<li>-41016: base64解密失败</li>*/
    public function decryptData($appid, $sessionKey, $encryptedData, $iv, &$data ){
		if (strlen($sessionKey) != 24) {
			return -41001;
		}
		$aesKey=base64_decode($sessionKey);

		if (strlen($iv) != 24) {
			return -41002;
		}
		$aesIV=base64_decode($iv);

		$aesCipher=base64_decode($encryptedData);

		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

		$dataObj=json_decode( $result );
		if( $dataObj  == NULL ){
			return -41003;
		}
		if( $dataObj->watermark->appid != $appid ){
			return -41003;
		}
		$data = $result;
		return 0;
	} 

     
    public function dopost($url,$post_data,$headers=''){
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		//不验证证书下同
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($headers)){
        	curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	} 
	
	//随机数
   	public function getRandom($param){

	    $str="0123456789abcdefghijklmnopqrstuvwxyz";
	
	    $key = "";
	
	    for($i=0;$i<$param;$i++){
	        $key .= $str{mt_rand(0,32)};
	    }
		return $key;
	}
     
}